<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>生成证书</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回列表</el-button>
      </div>

      <el-steps :active="active" finish-status="success" align-center style="margin-bottom: 30px;">
        <el-step title="选择模板"></el-step>
        <el-step title="选择数据"></el-step>
        <el-step title="生成证书"></el-step>
      </el-steps>

      <!-- 步骤1：选择模板 -->
      <div v-if="active === 0">
        <el-form :model="generateForm" ref="templateForm" label-width="100px">
          <el-form-item label="证书模板" prop="templateId" :rules="[{ required: true, message: '请选择证书模板', trigger: 'change' }]">
            <el-select v-model="generateForm.templateId" placeholder="请选择证书模板" style="width: 100%;" @change="handleTemplateChange">
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div v-if="generateForm.templateId" class="template-preview-container">
          <h3>模板预览</h3>
          <div v-html="templatePreview" class="template-preview"></div>
        </div>

        <div class="step-buttons">
          <el-button type="primary" @click="nextStep(0)">下一步</el-button>
        </div>
      </div>

      <!-- 步骤2：选择数据 -->
      <div v-if="active === 1">
        <el-form :model="generateForm" ref="dataForm" label-width="100px">
          <el-form-item label="生成方式">
            <el-radio-group v-model="generateForm.generateType">
              <el-radio label="single">单个生成</el-radio>
              <el-radio label="batch">批量生成</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="generateForm.generateType === 'single'">
            <el-form-item label="产品" prop="productId" :rules="[{ required: true, message: '请选择产品', trigger: 'change' }]">
              <el-select v-model="generateForm.productId" placeholder="请选择产品" style="width: 100%;" @change="handleProductChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="批次" prop="batchId" :rules="[{ required: true, message: '请选择批次', trigger: 'change' }]">
              <el-select v-model="generateForm.batchId" placeholder="请选择批次" style="width: 100%;" @change="handleBatchChange">
                <el-option
                  v-for="item in batchOptions"
                  :key="item.id"
                  :label="item.batchNo"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="检验任务" prop="taskId" :rules="[{ required: true, message: '请选择检验任务', trigger: 'change' }]">
              <el-select v-model="generateForm.taskId" placeholder="请选择检验任务" style="width: 100%;">
                <el-option
                  v-for="item in taskOptions"
                  :key="item.id"
                  :label="item.taskNo"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item label="产品" prop="productId" :rules="[{ required: true, message: '请选择产品', trigger: 'change' }]">
              <el-select v-model="generateForm.productId" placeholder="请选择产品" style="width: 100%;" @change="handleProductChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="批次列表" prop="batchIds" :rules="[{ required: true, message: '请选择至少一个批次', trigger: 'change' }]">
              <el-select v-model="generateForm.batchIds" multiple placeholder="请选择批次" style="width: 100%;">
                <el-option
                  v-for="item in batchOptions"
                  :key="item.id"
                  :label="item.batchNo"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="签发日期" prop="issueDate" :rules="[{ required: true, message: '请选择签发日期', trigger: 'change' }]">
            <el-date-picker
              v-model="generateForm.issueDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="签发人" prop="issuer" :rules="[{ required: true, message: '请输入签发人', trigger: 'blur' }]">
            <el-input v-model="generateForm.issuer" placeholder="请输入签发人"></el-input>
          </el-form-item>
        </el-form>

        <div class="step-buttons">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep(1)">下一步</el-button>
        </div>
      </div>

      <!-- 步骤3：生成证书 -->
      <div v-if="active === 2">
        <div class="generate-summary">
          <h3>证书生成信息确认</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="证书模板">{{ selectedTemplateName }}</el-descriptions-item>
            <el-descriptions-item label="生成方式">{{ generateForm.generateType === 'single' ? '单个生成' : '批量生成' }}</el-descriptions-item>
            <el-descriptions-item label="产品">{{ selectedProductName }}</el-descriptions-item>
            <el-descriptions-item label="批次" v-if="generateForm.generateType === 'single'">{{ selectedBatchNo }}</el-descriptions-item>
            <el-descriptions-item label="批次数量" v-else>{{ generateForm.batchIds ? generateForm.batchIds.length : 0 }}</el-descriptions-item>
            <el-descriptions-item label="签发日期">{{ generateForm.issueDate }}</el-descriptions-item>
            <el-descriptions-item label="签发人">{{ generateForm.issuer }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="generate-result" v-if="generateResult.length > 0">
          <h3>生成结果</h3>
          <el-table :data="generateResult" style="width: 100%">
            <el-table-column prop="certificateNo" label="证书编号" width="180"></el-table-column>
            <el-table-column prop="productName" label="产品" width="180"></el-table-column>
            <el-table-column prop="batchNo" label="批次"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  link
                  icon="el-icon-view"
                  @click="previewGeneratedCertificate(scope.row)"
                >预览</el-button>
                <el-button
                  size="mini"
                  link
                  icon="el-icon-printer"
                  @click="printGeneratedCertificate(scope.row)"
                >打印</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="step-buttons">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="generateCertificates" :loading="generating">生成证书</el-button>
          <el-button type="success" @click="goBack" v-if="generateResult.length > 0">完成</el-button>
        </div>
      </div>

      <!-- 预览证书对话框 -->
      <el-dialog title="预览证书" :visible.sync="previewOpen" width="800px" append-to-body>
        <div v-html="previewContent" class="certificate-preview"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
          <el-button type="primary" @click="printPreview">打 印</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listTemplate, previewTemplate } from "@/api/certificate/template";
import { batchGenerateCertificates, previewCertificate } from "@/api/certificate/manage";
import { listProduct } from "@/api/qep/product";
import { listBatch } from "@/api/qep/batch";
import { listInspectionTask } from "@/api/qep/inspection";

export default {
  name: "CertificateGenerate",
  data() {
    return {
      // 当前步骤
      active: 0,
      // 生成表单
      generateForm: {
        templateId: null,
        generateType: 'single',
        productId: null,
        batchId: null,
        batchIds: [],
        taskId: null,
        issueDate: new Date().toISOString().split('T')[0],
        issuer: this.$store.getters.name || ''
      },
      // 模板选项
      templateOptions: [],
      // 产品选项
      productOptions: [],
      // 批次选项
      batchOptions: [],
      // 任务选项
      taskOptions: [],
      // 模板预览
      templatePreview: '',
      // 生成中状态
      generating: false,
      // 生成结果
      generateResult: [],
      // 预览窗口
      previewOpen: false,
      // 预览内容
      previewContent: ""
    };
  },
  computed: {
    // 选中的模板名称
    selectedTemplateName() {
      const template = this.templateOptions.find(t => t.id === this.generateForm.templateId);
      return template ? template.name : '';
    },
    // 选中的产品名称
    selectedProductName() {
      const product = this.productOptions.find(p => p.id === this.generateForm.productId);
      return product ? product.name : '';
    },
    // 选中的批次编号
    selectedBatchNo() {
      const batch = this.batchOptions.find(b => b.id === this.generateForm.batchId);
      return batch ? batch.batchNo : '';
    }
  },
  created() {
    this.getTemplateOptions();
    this.getProductOptions();
  },
  methods: {
    // 获取模板选项
    getTemplateOptions() {
      listTemplate({ pageSize: 100 }).then(response => {
        this.templateOptions = response.rows || [];
      });
    },
    // 获取产品选项
    getProductOptions() {
      listProduct({ pageSize: 100 }).then(response => {
        this.productOptions = response.rows || [];
      });
    },
    // 获取批次选项
    getBatchOptions(productId) {
      if (productId) {
        listBatch({ productId, pageSize: 100 }).then(response => {
          this.batchOptions = response.rows || [];
        });
      } else {
        this.batchOptions = [];
      }
    },
    // 获取检验任务选项
    getTaskOptions(batchId) {
      if (batchId) {
        listInspectionTask({ batchId, pageSize: 100 }).then(response => {
          this.taskOptions = response.rows || [];
        });
      } else {
        this.taskOptions = [];
      }
    },
    // 处理模板变更
    handleTemplateChange(templateId) {
      if (templateId) {
        previewTemplate(templateId).then(response => {
          this.templatePreview = response.data;
        });
      } else {
        this.templatePreview = '';
      }
    },
    // 处理产品变更
    handleProductChange(productId) {
      this.generateForm.batchId = null;
      this.generateForm.batchIds = [];
      this.generateForm.taskId = null;
      this.getBatchOptions(productId);
    },
    // 处理批次变更
    handleBatchChange(batchId) {
      this.generateForm.taskId = null;
      this.getTaskOptions(batchId);
    },
    // 下一步
    nextStep(step) {
      if (step === 0) {
        this.$refs.templateForm.validate(valid => {
          if (valid) {
            this.active = 1;
          }
        });
      } else if (step === 1) {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.active = 2;
          }
        });
      }
    },
    // 上一步
    prevStep() {
      this.active -= 1;
    },
    // 返回列表
    goBack() {
      this.$router.push('/certificate/manage');
    },
    // 生成证书
    generateCertificates() {
      this.generating = true;
      
      // 构建请求数据
      const requestData = {
        templateId: this.generateForm.templateId,
        issueDate: this.generateForm.issueDate,
        issuer: this.generateForm.issuer
      };
      
      if (this.generateForm.generateType === 'single') {
        requestData.items = [{
          productId: this.generateForm.productId,
          batchId: this.generateForm.batchId,
          taskId: this.generateForm.taskId
        }];
      } else {
        requestData.items = this.generateForm.batchIds.map(batchId => ({
          productId: this.generateForm.productId,
          batchId: batchId
        }));
      }
      
      batchGenerateCertificates(requestData).then(response => {
        this.generateResult = response.data || [];
        this.generating = false;
        this.$message.success(`成功生成 ${this.generateResult.length} 份证书`);
      }).catch(() => {
        this.generating = false;
      });
    },
    // 预览生成的证书
    previewGeneratedCertificate(row) {
      previewCertificate(row.id).then(response => {
        this.previewContent = response.data;
        this.previewOpen = true;
      });
    },
    // 打印生成的证书
    printGeneratedCertificate(row) {
      previewCertificate(row.id).then(response => {
        const printContent = response.data;
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
          <html>
            <head>
              <title>证书打印</title>
              <style>
                body { font-family: Arial, sans-serif; }
                @media print {
                  body { margin: 0; padding: 0; }
                }
              </style>
            </head>
            <body>
              ${printContent}
              <script>
                window.onload = function() {
                  window.print();
                  setTimeout(function() { window.close(); }, 500);
                };
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      });
    },
    // 打印预览内容
    printPreview() {
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>证书打印</title>
            <style>
              body { font-family: Arial, sans-serif; }
              @media print {
                body { margin: 0; padding: 0; }
              }
            </style>
          </head>
          <body>
            ${this.previewContent}
            <script>
              window.onload = function() {
                window.print();
                setTimeout(function() { window.close(); }, 500);
              };
            </script>
          </body>
        </html>
      `);
      printWindow.document.close();
    }
  }
};
</script>

<style scoped>
.template-preview-container {
  margin-top: 20px;
  margin-bottom: 20px;
}
.template-preview {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 300px;
  max-height: 400px;
  overflow-y: auto;
}
.step-buttons {
  margin-top: 30px;
  text-align: center;
}
.generate-summary {
  margin-bottom: 30px;
}
.generate-result {
  margin-top: 30px;
  margin-bottom: 30px;
}
.certificate-preview {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 400px;
  max-height: 600px;
  overflow-y: auto;
}
</style> 